import router from '@/router/index.js'
import { getMenu } from '@/utils/auth' // 验权

const toRoute = function(item, pids, route, parentUrl = '') {
  const { url } = item
  if (url) {
    item.pids = pids
    route.push({
      path: `${parentUrl}${url}`,
      component: resolve => require([`@/views${parentUrl}${url}/index.js`], resolve),
      name: pids.concat(item.id).join('-'),
      meta: Object.assign(item, { pids, url: `${url}` }),
      noDropdown: true
    })
  }
  if (item.children && item.children.length) {
    for (let i = 0, len = item.children.length; i < len; i++) {
      toRoute(item.children[i], [...pids, item.id], route, item.url)
    }
  }
}

export function menuToRoute(menu) {
  const route = {
    path: '/',
    component: () => import("@/layout/index.vue"),
    chunkName: 'views/index',
    children: [],
    hidden: true
  }
  menu.forEach(item => {
    toRoute(item, [], route.children)
  })
  return [route]
}
export function addRoutes(menu) {
  router.addRoutes(menuToRoute(menu))
}

const menu = getMenu()
if (menu) {
  router.addRoutes(menuToRoute(menu))
}
